package think.thread.deadlock.c01;

import java.util.Random;
import java.util.concurrent.TimeUnit;

public class Philosopher implements Runnable {
	private Chopstick left;
	private Chopstick right;
	private int num;
	private int time;
	private int total;
	
	private int defaultMax=-1;

	public Philosopher(Chopstick left, Chopstick right, int num, int time) {
		this.left = left;
		this.right = right;
		this.num = num;
		this.time = time;
		this.total=defaultMax;
	}
	
	public Philosopher(Chopstick left, Chopstick right, int num, int time,int total) {
		this.left = left;
		this.right = right;
		this.num = num;
		this.time = time;
		this.total=total;
	}

	private Random random = new Random();

	public void pause() throws Exception {
		if (time <= 0) {
//			time = 1;
			return;
		}
		TimeUnit.MILLISECONDS.sleep(random.nextInt(time * 250));
	}

	public void run() {
		try {
			while (!Thread.interrupted()) {
				System.out.println(this + " thinking");
				pause();
				
				if(total>0&&num==total-1){
					left.take();
					System.out.println(this + " grabbing left");
					right.take();
					System.out.println(this + " grabbing right");
				}else{
					right.take();
					System.out.println(this + " grabbing right");
					left.take();
					System.out.println(this + " grabbing left");
				}
				
				System.out.println(this + " eating");
				pause();
				right.drop();
				System.out.println(this + " drop right");
				left.drop();
				System.out.println(this + " drop left");
			}
		} catch (Exception e) {
			// e.printStackTrace();
			System.out.println(this + " exiting via interrupt");
		}
	}

	public String toString() {
		return "philosopher " + num;
	}

}
